﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace HenrryTools.WinFormTools
{
    public partial class Base64WinForm : Form
    {
        public Base64WinForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 互换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTranSposition_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtRoot.Text.Trim()) && string.IsNullOrEmpty(txtReturn.Text.Trim()))
            {
                labMessages.Text = "两个输入框内容为空，内容互换失败！";
                labMessages.ForeColor = Color.Red;
                return;
            }
            string txtRootValue = txtRoot.Text;
            string txtRerurnValue = txtReturn.Text;
            txtRoot.Text = txtRerurnValue;
            txtReturn.Text = txtRootValue;
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEncodeBase64_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtRoot.Text))
            {
                labMessages.Text = "输入参数为空，请输入!";
                labMessages.ForeColor = Color.Red; return;
            }
            txtReturn.Text =Common.HenrryHelper.Base64Encode(Encoding.UTF8, txtRoot.Text).Replace(" ", "");

            DefaultLoadValue("加密成功，剪贴板已复制！", true);
        }
        /// <summary>
        /// 缓存并且判断最常使用得密钥  IsClipboard默认为True复制
        /// </summary>
        public void DefaultLoadValue(string Message, bool IsClipboard)
        {
            Properties.Settings.Default.Base64WinFormRoot = txtRoot.Text;//保存在Settings
            Properties.Settings.Default.Base64WinFormReturn = txtReturn.Text;//保存在Settings
            Properties.Settings.Default.Save();//保存

            if (IsClipboard)
            {
                Clipboard.SetDataObject(txtReturn.Text);//复制
            }

            labMessages.Text = Message;
            labMessages.ForeColor = Color.Green;
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBase64Decode_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtRoot.Text))
            {
                labMessages.Text = "输入参数为空，请输入!";
                labMessages.ForeColor = Color.Red; return;
            }
            //将空格替换为加号  
            string text = txtRoot.Text.Replace(" ", "+");
            if ((text.Length % 4) != 0)
            {
                labMessages.Text = "包含不正确的BASE64编码!";
                labMessages.ForeColor = Color.Red;
                return;
            }
            if (!Regex.IsMatch(text, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
            {
                labMessages.Text = "包含不正确的BASE64编码!";
                labMessages.ForeColor = Color.Red;
                return;
            }
            txtReturn.Text = Base64Decode(Encoding.UTF8, text);
            DefaultLoadValue("解密成功，剪贴板已复制！", true);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="encodeType">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string Base64Decode(Encoding encodeType, string result)
        {
            string decode = string.Empty;
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encodeType.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }
        /// <summary>
        ///加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base64WinForm_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.Base64WinFormRoot) || !string.IsNullOrWhiteSpace(Properties.Settings.Default.Base64WinFormReturn))
            {
                txtRoot.Text = Properties.Settings.Default.Base64WinFormRoot;//保存在Settings
                txtReturn.Text = Properties.Settings.Default.Base64WinFormReturn;//保存在Settings
            }
        }
        /// <summary>
        /// 文件转base64
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Filetobase64_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            string file = "";
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = dialog.FileName;
            }
            if (string.IsNullOrEmpty(file)) return;
            //文件转转base64
            FileStream fsForRead = new FileStream(file, FileMode.Open);//文件路径
            string base64Str = "";
            try
            {
                //读写指针移到距开头10个字节处
                fsForRead.Seek(0, SeekOrigin.Begin);
                byte[] bs = new byte[fsForRead.Length];
                int log = Convert.ToInt32(fsForRead.Length);
                //从文件中读取10个字节放到数组bs中
                fsForRead.Read(bs, 0, log);
                base64Str = Convert.ToBase64String(bs);
                txtReturn.Text = base64Str;
                DefaultLoadValue("文件转Base64成功，剪贴板已复制！", true);
            }
            catch (Exception ex)
            {
                txtReturn.Text = base64Str;
            }
            finally
            {
                fsForRead.Close();
            }
        }
        /// <summary>
        /// Base64转PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnToPDF_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtRoot.Text))
            {
                labMessages.Text = "输入参数为空，请输入!";
                labMessages.ForeColor = Color.Red; return;
            }
            try {
                //解析base64转PDF
                var baseStr = txtRoot.Text;// PDFBase64格式的文件
                byte[] imageBytes = Convert.FromBase64String(baseStr);
                var filename = "D:/Base64.pdf";//所要保存的相对路径及名字 

                //删除D盘Base64.pdf文件
                System.IO.File.Delete(filename);

                FileStream fs = new FileStream(filename, FileMode.CreateNew);
                fs.Write(imageBytes, 0, imageBytes.Length);
                fs.Close();
                //打开本地wps应用展示PDF
                System.Diagnostics.Process pro = new System.Diagnostics.Process();
                pro.StartInfo.FileName = "wps.exe";
                pro.StartInfo.Arguments = "D:/Base64.pdf";
                pro.Start();

                DefaultLoadValue("文件保存在D盘，名称为Base64.pdf", false);
                labMessages.ForeColor = Color.Green;
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
